package com.xiaozheng.jdbcTemplate;

import com.xiaozheng.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Package: com.xiaozheng.jdbcTemplate
 * @ClassName: JdbcTemplateDemo
 * @Author: 小政同学    QQ:xiaozheng666888@qq.com
 * @CreateTime: 2020/10/20 12:55
 * @What_is_this_file_for: 这个文件是用来做什么的?
 * @Description: 描述
 */
public class JdbcTemplateDemo {
    public static void main(String[] args) {
        /*//准备数据源：Spring内置数据源
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis_spring?serverTimezone=GMT");
        ds.setUsername("root");
        ds.setPassword("Zongroot");
        //1.创建JdbcTemplate对象
        //JdbcTemplate jt = new JdbcTemplate();
        //2.给jt对象设置数据源
        //jt.setDataSource(ds);*/

        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //获取对象
        JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);


        //执行操作
        //jt.execute("insert into accountbak(name,money)values('张三',1000)");
        //jt.query("select * from accountbak where money>?",new AccountRowMapper(),100f);
        List<Account> accounts = jt.query("select * from accountbak where money > ?", new BeanPropertyRowMapper<Account>(Account.class), 100f);
        for (Account account : accounts) {
            System.out.println(account.toString());
        }
        jt.update("insert into account(name,money)values(?,?)", new BeanPropertyRowMapper<Account> (Account.class), "zhang",1000f);
        jt.update("delete from accountback where id = ?", new BeanPropertyRowMapper<Account>(Account.class), 1);
        jt.queryForObject("select * from accountbak where id = ?", new BeanPropertyRowMapper<Account>(Account.class), 5);

    }
}

/**
 * 定义Account的封装策略
 */
class AccountRowMapper implements RowMapper<Account>{

    /**
     * 把结果集中的数据封装到Account中，然后由Spring把每个Account加到集合中
     * @param rs
     * @param rowNum
     * @return
     * @throws SQLException
     */
    @Override
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getDouble("money"));
        return account;
    }
}
